<template>
  <transition :name="`my-toast--${position}-fade`" @after-leave="handleAfterLeave">
    <div class="my-toast" :class="['my-toast--' + position ,'my-toast--' + type]" v-show="show">
      <div class="my-toast__title">{{title}}</div>
    </div>
  </transition>
</template>

<script>
export default {
  name: "MyToast",
  data() {
    return {
      title: "", // 标题
      show: false, // 是否显示
      position: "top", // 显示位置
      duration: 3000, // 显示时间
      type: "default", // 显示类型
      onClose: null, // 关闭回调
      closed: false, // 是否关闭
      timer: null, // 定时器
    };
  },
  watch: {
    closed(newVal) {
      if (newVal) {
        this.show = false;
      }
    },
  },
  mounted() {
    this.startTimer();
  },
  methods: {
    close() {
      this.closed = true;
      if (typeof this.onClose === "function") {
        this.onClose(this);
      }
    },
    updateData(data) {
      this.clearTimer();
      Object.keys(data).forEach((k) => {
        this[k] = data[k];
      });
      this.startTimer();
    },
    startTimer() {
      if (this.duration > 0) {
        this.timer = setTimeout(() => {
          if (!this.closed) {
            this.close();
          }
        }, this.duration);
      }
    },
    clearTimer() {
      clearTimeout(this.timer);
    },
    handleAfterLeave() {
      this.$destroy(true);
      this.$el.parentNode.removeChild(this.$el);
    },
  },
};
</script>

<style lang="scss">
.my-toast {
  min-width: 300px;
  box-sizing: border-box;
  border-radius: 4px;
  z-index: 1080;
  position: fixed;
  left: 50%;
  transition: 0.3s;
  overflow: hidden;
  padding: 15px;
  display: flex;
  align-items: center;

  &.my-toast--default {
    border: 1px solid #b3e8ff;
    background-color: #ccf0ff;
    color: #00b2ff;
  }

  &.my-toast--success {
    border: 1px solid #cbf0dc;
    background-color: #dcf5e7;
    color: #50cd89;
  }

  &.my-toast--warning {
    border: 1px solid #ffeeb3;
    background-color: #fff4cc;
    color: #ffc700;
  }

  &.my-toast--danger {
    border: 1px solid #fbc6d3;
    background-color: #fcd9e2;
    color: #f1416c;
  }
}

.my-toast--top {
  top: 20px;
  transform: translate(-50%, 0);
}

.my-toast--center {
  top: 50%;
  transform: translate(-50%, -50%);
}

.my-toast--bottom {
  bottom: 20px;
  transform: translate(-50%, 0);
}

.my-toast__title {
  font-size: 14px;
  line-height: 1;
}

.my-toast--top-fade-enter,
.my-toast--top-fade-leave-active {
  opacity: 0;
  transform: translate(-50%, -100%);
}

.my-toast--center-fade-enter,
.my-toast--center-fade-leave-active {
  opacity: 0;
  transform: translate(-50%, 0%);
}

.my-toast--bottom-fade-enter,
.my-toast--bottom-fade-leave-active {
  opacity: 0;
  transform: translate(-50%, 100%);
}
</style>